import Exif from "exif-js";   //获取照片元信息
export default {
    //---------属性------------
    attrs:{
        file:null,   //上传的文件
        img:{   //照片
            img:null,  //图片
            width:0,
            height:0,
            exif_orientation:1   //照片的选择角度
        },
        compress:true,  //是否压缩
        max_size:1*1024*1024,   //压缩图片大小
        target_width:750,  //压缩的目标宽度
        quality:0.8,  //生成图片的质量
        canvas:null,  //canvas
        context:null,   //context
        create_base64:'',  //生成的base64
        ios:!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),  //是否为ios
        android:navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1  //是否为安卓
    },

    //-------方法----------
    /**
     * 获取图片
     * @param obj  对象参数
     */
    get(obj){
        return new Promise((success,error)=>{
            this.attrs = Object.assign(this.attrs,obj);
            this.getWH()
                .then(()=>{
                    this.getOrientation();
                })
                .then(()=>{
                    if(this.attrs.file.size <= this.attrs.max_size){
                        success(this.attrs.file);
                    }
                })
                .then(()=>{
                    this.createCanvas();
                })
                .then(()=>{
                    if(this.attrs.ios){
                        return this.iosHandle();
                    }else{
                        return this.androidHandle();
                    }
                })
                .then(()=>{
                    success(this.attrs.file);
                })
                .catch((err)=>{
                    error(err);
                });
        });
    },

    /**
     * 获取图片的宽高
     */
    getWH(){
        return new Promise((success)=>{
            let self = this;
            let fileRead = new FileReader();
            fileRead.readAsDataURL(this.attrs.file);
            fileRead.onload = function(){
                let base64 = this.result;
                self.attrs.img.img = new Image();
                self.attrs.img.img.src = base64;
                self.attrs.img.img.onload = function () {
                    self.attrs.img.width = this.width;
                    self.attrs.img.height = this.height;
                    success();
                }
            }
        });
    },

    /**
     * 获取照片Orientation角度
     */
    getOrientation(){
        return new Promise((success)=>{
            let self = this;
            Exif.getData(this.attrs.img.img,function(){
                self.attrs.img.exif_orientation = Exif.getTag(this,"Orientation");
                success();
            });
        });
    },

    /**
     * 创建canvas
     */
    createCanvas(){
        this.attrs.canvas = document.createElement('canvas');
        this.attrs.context = this.attrs.canvas.getContext('2d');
    },

    /**
     * IOS处理
     */
    iosHandle(){
            switch(this.attrs.img.exif_orientation){
                case 6:
                    return this.rotateImg('left',true)
                        .then(()=>{
                            this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',this.attrs.quality);
                            this.attrs.file = this.crateFile();
                        });
                case 8:
                    return this.rotateImg('right',true)
                        .then(()=>{
                            this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',this.attrs.quality);
                            this.attrs.file = this.crateFile();
                        });
                case 3:
                    this.rotateImg('right',false);
                    return this.rotateImg('right',true)
                        .then(()=>{
                            this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',this.attrs.quality);
                            this.attrs.file = this.crateFile();
                        });
                default:
                    this.defaultHandle();
                    this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',this.attrs.quality);
                    this.attrs.file = this.crateFile();
                    break;
            }
    },

    /**
     * 安卓处理
     */
    androidHandle(){
        let scale = this.attrs.img.width / this.attrs.img.height;
        this.attrs.canvas.width = this.attrs.target_width;
        this.attrs.canvas.height = this.attrs.target_width / scale;
        this.attrs.context.drawImage(
            this.attrs.img.img,
            0,
            0,
            this.attrs.img.width,
            this.attrs.img.height,
            0,
            0,
            this.attrs.canvas.width,
            this.attrs.canvas.height
        );
        this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',this.attrs.quality);
        this.attrs.file = this.crateFile();
    },

    /**
     * 默认处理，不旋转
     */
    defaultHandle(){
        let scale = this.attrs.img.width / this.attrs.img.height;
        this.attrs.canvas.width = this.attrs.target_width;
        this.attrs.canvas.height = this.attrs.target_width / scale;
        this.attrs.context.drawImage(
            this.attrs.img.img,
            0,
            0,
            this.attrs.img.width,
            this.attrs.img.height,
            0,
            0,
            this.attrs.canvas.width,
            this.attrs.canvas.height
        );
    },

    //对图片旋转处理 added by lzk
    rotateImg(direction,end){
        //alert(img);
        //最小与最大旋转方向，图片旋转4次后回到原方向
        var min_step = 0;
        var max_step = 3;
        //var img = document.getElementById(pid);
        if (this.attrs.img.img == null)return;
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错
        var height = this.attrs.img.height;
        var width = this.attrs.img.width;
        //var step = img.getAttribute('step');
        var step = 2;
        if (step == null) {
            step = min_step;
        }
        if (direction == 'right') {
            step++;
            //旋转到原位置，即超过最大值
            step > max_step && (step = min_step);
        } else {
            step--;
            step < min_step && (step = max_step);
        }
        //旋转角度以弧度值为参数
        var degree = step * 90 * Math.PI / 180;
        switch (step) {
            case 0:
                this.attrs.canvas.width = width;
                this.attrs.canvas.height = height;
                this.attrs.context.drawImage(this.attrs.img.img, 0, 0);
                break;
            case 1:
                this.attrs.canvas.width = height;
                this.attrs.canvas.height = width;
                this.attrs.context.rotate(degree);
                this.attrs.context.drawImage(this.attrs.img.img, 0, -height);
                break;
            case 2:
                this.attrs.canvas.width = width;
                this.attrs.canvas.height = height;
                this.attrs.context.rotate(degree);
                this.attrs.context.drawImage(this.attrs.img.img, -width, -height);
                break;
            case 3:
                this.attrs.canvas.width = height;
                this.attrs.canvas.height = width;
                this.attrs.context.rotate(degree);
                this.attrs.context.drawImage(this.attrs.img.img, -width, 0);
                break;
        }
        if(!end) return;
        this.attrs.create_base64 = this.attrs.canvas.toDataURL('image/jpeg',1);
        return this.baseToImg()
            .then(()=>{
               return this.defaultHandle();
            });
    },

    /**
     * 将base64转为img
     */
    baseToImg(){
        var self = this;
        return new Promise((success)=>{
            this.attrs.img.img = new Image();
            this.attrs.img.img.src = this.attrs.create_base64;
            this.attrs.img.img.onload = function () {
                self.attrs.img.width = this.width;
                self.attrs.img.height = this.height;
                success();
            }
        });
    },

    //创建File对象
    crateFile(){
        var arr = this.attrs.create_base64.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        let blob = new Blob([u8arr],{type: mime});
        return new File([blob],this.attrs.file.name);
    }
}
